package com.atech.ace.web;

import java.io.IOException;
import java.sql.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atech.ace.business.client.OrderAdministrationRemote;
import com.atech.ace.entity.Order;
import com.atech.ace.entity.Orderitem;
import com.atech.ace.entity.Product;
import com.atech.ace.entity.User;
import com.atech.ace.web.cart.ShoppingCart;

/**
 * Servlet implementation class OrderController
 */
public class OrderController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String ADD_TO_CART = "/cart";
	private static final String CHECKOUT = "/checkout";
	private static final String PAYMENT = "/payment";
	
    @EJB
    private OrderAdministrationRemote admin;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getServletPath();
		if(action.equals(ADD_TO_CART))
		{
			ShoppingCart cart = ( ShoppingCart ) request.getSession().getAttribute("cart");
			if(cart == null) 
			{
				cart = new ShoppingCart();
			}
			
			String productId = request.getParameter("pid");
			Map products = admin.getAllProducts();
			Product p = new Product();
			p.setProductId(Integer.parseInt(productId));
			p.setCurrentQuantity(Integer.parseInt(request.getParameter("qty")));
			p.setPrice(((Product)products.get(Integer.parseInt(productId))).getPrice());
			p.setName(((Product)products.get(Integer.parseInt(productId))).getName());
			cart.addOrUpdateProduct(p);
			request.getSession().setAttribute("cart", cart);
		}
		else if(action.equals(CHECKOUT))
		{
			Order o = new Order();
			ShoppingCart cart = ( ShoppingCart ) request.getSession().getAttribute("cart");
			Map items = cart.getProducts();
			HashSet orderItems = new HashSet(items.size());
			
			Iterator i = items.entrySet().iterator();
			double total = 0.0;
			
			while(i.hasNext())
			{
				Map.Entry me = ( Map.Entry ) i.next();
				Product p = ( Product ) me.getValue();
				Orderitem oi = new Orderitem();
				oi.setProduct(p);
				oi.setPriceAtPurchase(p.getPrice());
				oi.setQuantity(p.getCurrentQuantity());
				total += (p.getPrice() * p.getCurrentQuantity());
				orderItems.add(oi);				
			}
			
			o.setOrderDate(new Date(System.currentTimeMillis()));
			o.setOrderitems(orderItems);
			o.setTotal(total);
			o.setUser((User)request.getSession().getAttribute("user"));
			
			admin.createOrder(o);
			
			getServletConfig().getServletContext().getRequestDispatcher("/store/payment.jsp").forward(request,response);
		}
		else if (action.equals(PAYMENT))
		{
			getServletConfig().getServletContext().getRequestDispatcher("/store/thankyou.jsp").forward(request,response);
		}
	}

}
